package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session) {

        //获取手机号
        String phone = user.getPhone();
        //手机号非空校验
        if (StringUtils.isEmpty(phone)) {
            return R.error("发送验证码失败");
        }
        //生成随机4位数验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("短信验证码:{}", code);

        //调用阿里云提供的短信服务API完成发送短信
        //SMSUtils.sendMessage("阿里云短信测试","SMS_154950909","19156537568","code");


        //需要将生成的验证码保存到Session  setAttribute(senssion名称String类型,数据)
        session.setAttribute(phone,code);

        //生成的验证码存入Redis，设置过期时间
        //redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        return R.success("发送验证码成功");
    }

    /**
     * 用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());

        //获取用户填写手机号
        String phone = map.get("phone").toString();
        //获取用户填写验证码
        String code = map.get("code").toString();

        //从Session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);

        //从Redis中获取验证码
        //Object codeInSession = redisTemplate.opsForValue().get(phone);
        //比对
        if (codeInSession != null && codeInSession.equals(code)) {
            //登录成功，获取user对象、
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            if (user == null) {
                //新用户注册
                user = new User();
                user.setPhone(phone);
                //0禁用，1正常
                user.setStatus(1);
                //存入数据库
                userService.save(user);
            }
            //将用户id存入session 不被拦截
            session.setAttribute("user", user.getId());

            return R.success(user);

        }

        //验证码不正确登录失败
        return R.error("登录失败");
    }

    /**
     * 用户登出
     *
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session) {

        //移除当前登录信息 用户id
        session.removeAttribute("user");

        return R.success("登录成功");
    }
}


